﻿/******************************************************   
创建者: 梁家健
创建时间: 2017-07-28
修改:
修改时间: 
功能: 零售分部用户
 ******************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BaseAPI.model;
using com.nm.ApiServer;
using com.nm.Attributes;
using com.nm.ApiServer.Attributes;
using com.nm.db.Models.Systems;
using com.nm.library;
using EntityFramework.Extensions;

namespace BaseAPI
{
    [Description("零售分部用户信息")]
    public class OperationAreaUserHandler : BaseHandler
    {
        [MustLogin]
        [Description("零售区域用户列表")]
        [ReturnType(typeof(IList<OperationAreaUserData.UserListModel>))]
        public ApiResult GetOperationAreaUserList([ParamDescription("零售区域")] string OperationAreaID)
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                var dc = new SysEntities();
                #region 原方法,区分公司下的用户
                //                var sql = $@"--查询树状结构某节点下的所有子节
                //WITH    cte_child ( DeptID, ParentID, DeptContent, CompanyID, UserID, UserName, OperationAreaID )
                //          AS (
                //               --起始条件 
                //               SELECT   d.DeptID ,
                //                        d.ParentID ,
                //                        d.DeptContent ,
                //                        d.CompanyID ,
                //                        t1.UserID ,
                //                        t1.UserName ,
                //                        t1.OperationAreaID
                //               FROM     sys_dept d
                //                        INNER JOIN ( SELECT u.UserID ,
                //                                            u.UserName ,
                //                                            d.DeptCode ,
                //                                            oau.OperationAreaID
                //                                     FROM   dbo.sys_users u
                //                                            INNER JOIN dbo.sys_dept d ON u.DeptID = d.DeptID
                //                                            INNER JOIN dbo.sys_operationArea_user oau ON u.UserID = oau.UserID
                //                                   ) t1 --列出父节点查询条件
                //                        ON d.DeptCode = t1.DeptCode
                //               WHERE    d.IsRemove = 0
                //               UNION ALL
                //                            --递归条件
                //               SELECT   a.DeptID ,
                //                        a.ParentID ,
                //                        a.DeptContent ,
                //                        a.CompanyID ,
                //                        b.UserID ,
                //                        b.UserName ,
                //                        b.OperationAreaID
                //               FROM     sys_dept a
                //                        INNER JOIN cte_child b ON ( a.DeptID = b.ParentID )  --根据查询到的父节点(a.Parent)，通过CTE递归查询出其子节点(b.ID)
                //             )
                //    SELECT  DeptID ,
                //            ParentID ,
                //            DeptContent ,
                //            CompanyID ,
                //            UserID ,
                //            UserName ,
                //            OperationAreaID
                //    FROM    cte_child
                //    WHERE   ParentID = 1
                //            AND CompanyID = '{UserInfo.UserCompanyId}' ";
                //                var list = dc.Database.SqlQuery<OperationAreaUserData.ListModel>(sql);
                #endregion
                var allList = (from oa in dc.sys_operationArea_user
                               join user in dc.sys_users on oa.UserID equals user.UserID
                               where
                               user.IsRemove == false && user.IsEffective
                               select oa.UserID).ToList();
                var list = dc.sys_operationArea_user.Where(t => t.OperationAreaID == (OperationAreaID)).Select(t => t.UserID).ToList();
                var result = new OperationAreaUserData.UserListModel()
                {
                    AllChooseList = allList.Except(list).ToList(),
                    CurrentUserList = list
                };
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        /// Writer：梁家健
        /// Create Date：2017-03-15
        [JsonType]
        [MustLogin]
        [Description("修改零售分部用户信息")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult SaveOperationAreaUser([ParamDescription("零售区域")] OperationAreaUserData.UserAreaList param)
        {
            try
            {
                if (param == null) return Error("参数对象为空");
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }

                var dc = new SysEntities();
                dc.sys_operationArea_user.Where(t => t.UserID == param.UserId).Delete();
                if (param.OperationAreaID != null)
                {
                    foreach (var item in param.OperationAreaID)
                    {
                        if (item != "default")
                        {
                            var it = new sys_operationArea_user
                            {
                                OperationAreaID = item,
                                UserID = param.UserId
                            };
                            dc.sys_operationArea_user.Add(it);
                        }
                    }
                }

                dc.SaveChanges();

                return Success(0);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        [MustLogin]
        [Description("根据用户ID获取对应的零售区域用户列表")]
        [ReturnType(typeof(IList<OperationAreaUserData.UserListModel>))]
        public ApiResult GetOperationAreaListByUser([ParamDescription("零售区域")] string UserId)
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                int id = 0;
                if (string.IsNullOrEmpty(UserId) || !int.TryParse(UserId, out id))
                {
                    return Error("找不到用户ID");
                }
                var dc = new SysEntities();
                var allList = (from oa in dc.sys_operationArea_user
                               join user in dc.sys_users on oa.UserID equals user.UserID
                               where
                               user.IsRemove == false && user.IsEffective
                               select oa.UserID).ToList();
                //查找
                int temp = Convert.ToInt32(UserId);
                var list = dc.sys_operationArea_user.Where(t => t.UserID == temp).Select(t => t.OperationAreaID).ToList();
                var result = new OperationAreaUserData.UserAreaList()
                {
                    OperationAreaID = list
                };
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        #region GetOperationList 获取指定用户的零售分部

        /// <summary>
        /// 获取指定用户的零售分部
        /// 作者：dmhai
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<string> GetOperationList([ParamDescription("用户ID")] int userId)
        {
            try
            {
                var dc = new SysEntities();
                var operationAreaList = dc.sys_operationArea_user.Where(x => x.UserID == userId).ToList();
                var list = new List<string>();
                foreach (var o in operationAreaList)
                {
                    list.Add(o.OperationAreaID);
                }
                return list;
            }
            catch (Exception ex)
            {
                return new List<string>();
            }
        }

        #endregion


    }
}
